const Koa = require('koa')
const app = new Koa()

require('./models/Middle')
const { loadRoutes, loadMiddleware, loadInterceptor, apiInterceptor } = require('./config/app.middleware')

const serve = require('koa-static')
const path = require('path')

// koa-static
app.use(serve(path.join(__dirname, 'public')))

// 加载其他中间件
loadMiddleware(app)

app.use(async (ctx, next) => {
  try {
    await next()
  } catch (error) {
    // koa全局错误处理on,emit-----主动提交错误（如果直接）
    ctx.app.emit('error', error, ctx)
  }
})

// koa全局错误处理
app.on('error', async(error, ctx) => {
  ctx.status = 200
  ctx.body = {
    code: error.status,
    msg: error.original ? error.original.sqlMessage : error.message
  }
})


// 加载全局拦截器
loadInterceptor(app)
// 加载接口拦截器
apiInterceptor(app)


// 加载路由自动注册
loadRoutes(app)

app.listen(8081, () => {
  console.log('app is running at 8081...')
})